package zdream.control.foe.mm;

import java.util.function.BooleanSupplier;

import zdream.control.world.buff.AttackModule;
import zdream.control.world.MFoe;
import zdream.control.world.buff.HealthModule;
import zdream.control.world.MHookType;
import zdream.control.world.MHooks;
import zdream.control.world.TerrainHandler;
import zdream.control.world.Ticker;

import static zdream.control.world.MFoeConstants.*;

/**
 * <p>洛克人的子弹 一级蓄力 (要蓄力一秒)
 * <p>
 * 默认伤害为 2. 如果碰到的怪没死则不消失
 * 水平移动速度为 24 块/秒.
 * <li>最长寿命为 1 秒, 如果在房间外超过 0.05 秒也会被回收.
 * <li>屏幕上最多 3 个子弹. 如果子弹出了屏幕但是仍然在房间内,
 * 不会回收, 且武器加一个空槽. (可以让你再发一颗子弹)
 * </li>
 * </p>
 * 
 * @author Zdream
 * @since 0.0.1
 * @date 2022-06-15 (created)
 */
public class MegaManBusterRestoreL1 extends MFoe {
	public static final String NAME = "MegaManBusterRestoreL1";
	public static final String PATTERN_RELEASE = "released";
	public final MegaMan parent;

	public MegaManBusterRestoreL1(MegaMan parent) {
		super(parent.world);
		this.parent = parent;
		type = TYPE_BULLET;
		side = parent.side;
	}

	@Override
	public String foeName() {
		return NAME;
	}

	@Override
	public void init() {
		createNormalPattern().withRectangle(-3/24f, -6/24f, 6/24f, 12/24f).apply();
		createPattern(PATTERN_RELEASE).withRectangle(-6/24f, -6/24f, 12/24f, 12/24f);

		attackModule = buildAttackModule()
				.damage(2)
				.damageLevel(DAMAGE_LEVEL_SPECIAL)
				.ignoreSide(side)
				.targetTypesIsEntity()
				.destroyWhenEnemyNotDie()
				.create();
		healthModule = buildHealthModule()
				.maxAgeInMS(1000)
				.outsideDestroyThreshold(50)
				.create();

		terrainHandler = new TerrainHandler(world);
		terrainHandler.floating = true;

		onHook(MHookType.TICK)
				.handle(this::handleMotion)
				.buildAndSave();
		releaseCheckCleaner = onHook(MHookType.TICK)
				.handle(this::checkRelease)
				.withPriority(1)
				.buildAndSave();
	}

	AttackModule attackModule;
	HealthModule healthModule;

	BooleanSupplier releaseCheckCleaner;

	/* **********
	 *   盒子   *
	 ********** */

	int vx = 24, vy;
	/**
	 * 0.333 秒前 released = false, 之后 released = true
	 */
	boolean released = false;

	private void checkRelease(MHooks.MHookContext rawContext) {
		Ticker ticker = world.ticker;
		if (ticker.foePaused) {
			return;
		}

		if (!released && age >= 33) {
			applyPattern(PATTERN_RELEASE);
			released = true;
			releaseCheckCleaner.getAsBoolean();
		}
	}

	private void handleMotion(MHooks.MHookContext rawContext) {
		Ticker ticker = world.ticker;
		if (ticker.foePaused) {
			return;
		}

		float vx = (orientation) ? this.vx : -this.vx;
		float vy = this.vy;

		velocityX = vx * ticker.duration;
		velocityY = vy * ticker.duration;
		terrainHandler.submitMotion(this);
	}
}
